<template>
    <div id="app">
        <el-card class="box-card">
            <el-input v-model="caseIdorName" placeholder="请输入病理号或患者姓名" style="width: 200px;" clearable @clear="bindEmrCaseData(true)"></el-input>
            <el-button type="info" style="float: right;" @click="bindEmrCaseData(true)">搜索</el-button>
        </el-card>
        <div v-loading="loading" element-loading-text="加载中..." style="width: 100px;margin: 0 auto;position: relative;top: 250px;">
        </div>
        <div v-if="loading == false">
            <el-empty v-if="emrCaseOrMsg.length == 0" description="暂无数据!" />
            <el-card class="box-card" v-for="(item, index) in emrCaseOrMsg" :key="item.id" v-loading="cardLoading[index]" element-loading-text="加载中...">
                <template #header>
                    <div class="card-header">
                        {{ item.send_hospital }} （病理号：{{ item.id }}，患者姓名：{{ item.name }}）
                    </div>
                </template>
                <div v-for="msg in item.emrCaseMsgList" :key="item.id">
                    <div>
                        <el-avatar :src="getUserNameAndPhoto(msg).photo" style="float: left;" />
                        <div style="position: relative; ">
                            <div style="font-weight: bold;position: relative;left: 10px;">{{ getUserNameAndPhoto(msg).name
                            }} <span style="font-size: 12px;font-weight: normal;">{{ timeago(msg.createDate) }}</span>
                            </div>
                            <div style="position: relative;left: 10px;top: 5px;">{{ msg.content }}</div>
                            <div style="float: right;position: relative;bottom: 30px;">{{ formatDate(msg.createDate) }}
                            </div>
                        </div>
                    </div>
                    <div style="clear:both;"></div>
                    <hr />
                </div>
                <el-input type="textarea" v-model="content[index]" style="width: 100%;" :rows="3" placeholder="请输入内容"></el-input>
                <el-button type="success" style="float: right;margin: 10px 0px;"
                    @click="sendMsg(item, index)">发送消息</el-button>
            </el-card>
            <div style="font-size: 12px; padding: 5px 12px 10px;">共 {{ emrCaseOrMsg.length }} 条</div>
        </div>
    </div>
</template>

<script setup>
import { getEmrCaseOrMsg, addMsg } from '@/api/phy/emrcase'
import { getListUser, getUserProfile } from '@/api/system/user'
import { ElMessage } from 'element-plus'
import { timeago } from '@/utils/formatTime'

const caseIdorName = ref('');
const emrCaseOrMsg = ref([]);
const userList = ref([]);
const userInfo = ref([]);
const content = ref([]);
const loading = ref(true);
const cardLoading = ref([])
const indexA = ref()


// 获取所有病例留言
async function bindEmrCaseData(bool) {
    if(bool != undefined) loading.value = bool;
    if(indexA.value != undefined) cardLoading.value[indexA.value] = true;
    await getEmrCaseOrMsg(caseIdorName.value).then(response => {
        setTimeout(() => {
            emrCaseOrMsg.value = response.data;
            if(loading.value) loading.value = false;
            if(indexA.value != undefined) {
                cardLoading.value[indexA.value] = false
                cardLoading.value = [];
                indexA.value = undefined;
            };
        }, 1500);
    })
}

// 获取所有用户
async function bindUserList() {
    await getListUser().then(res => {
        userList.value = res.data;
    })
}

// 时间格式化
function formatDate(timestamp) {
    var date = new Date(timestamp)
    var year = date.getFullYear(),
        month = (date.getMonth() + 1).toString().padStart(2, 0),//月份是从0开始的
        day = date.getDate().toString().padStart(2, 0),
        hour = date.getHours().toString().padStart(2, 0),
        min = date.getMinutes().toString().padStart(2, 0),
        sec = date.getSeconds().toString().padStart(2, 0);
    var dateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec;
    return dateTime;
}

// 获取用户姓名和头像
function getUserNameAndPhoto(msg) {
    var user = {
        name: ''
    }
    userList.value.forEach(item => {
        if (item.use_by == msg.createBy) {
            user = item;
            return;
        }
    })
    user.name == '' ? user.name = '该用户不存在' : user;
    return user;
}

// 绑定登录用户信息
async function bindUserInfo() {
    await getUserProfile().then(res => {
        userInfo.value = res.data;
    })
}

// 发送消息
async function sendMsg(emrCase, index) {
    indexA.value = index;
    if (content.value == '') {
        ElMessage({
            showClose: true,
            message: '消息不能为空！',
            type: 'warning'
        })
        return;
    }
    var emrCaseMsg = {
        caseId: emrCase.id,
        content: content.value[index],
        receiverId: emrCase.create_by,
        createBy: userInfo.value.use_by,
        createDate: formatDate(new Date()),
        accountId: emrCase.account_id
    }
    await addMsg(emrCaseMsg).then(() => {
        ElMessage({
            showClose: true,
            message: '发送成功！',
            type: 'success'
        })
        content.value = [];
        bindEmrCaseData();
    }).catch(error => {
        ElMessage({
            showClose: true,
            message: '错误:' + error,
            type: 'error'
        })
    })
}

bindEmrCaseData();
bindUserList();
bindUserInfo();
</script>

<style lang="scss" scoped>
#app {
    background-color: #eee;
}

.box-card {
    margin: 10px 8px;
    font-size: 12px;
}

.card-header {
    font-size: 16px;
    font-weight: bold;
}
</style>
